package com.xxxx.server.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;



@RestController
public class CaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @ApiOperation(value = "获取验证码")
    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-Control","no-store , no-cache , must-revalidate");
        response.addHeader("Cache-Control","post-check=0, pre-check=0");
        response.setHeader("Pragma","no-cache");
        response.setContentType("image/jpeg");

        String captcha=defaultKaptcha.createText();
        request.getSession().setAttribute("captcha",captcha);
        System.out.println("验证码内容"+captcha);

        BufferedImage image= defaultKaptcha.createImage(captcha);
        ServletOutputStream servletOutputStream =null;

        try {
            servletOutputStream=response.getOutputStream();
            ImageIO.write(image,"jpg",servletOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (servletOutputStream!=null){
                try {
                    servletOutputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }


    }
}
